﻿#region License
// <copyright file="ObjectContextExtensions.cs" company="Kopigi - Marc Plessis">
// Copyright © Kopigi 2011
// </copyright>
// ****************************************************************************
// <author>Marc Plessis</author>
// <email>marc.plessis@kopigi.fr</email>
// <date>03/04/2011</date>
// <project>Biwo</project>
// <web>http://www.kopigi.fr/biwo</web>
// <license>
// See license.txt in this solution or http://www.microsoft.com/opensource/licenses.mspx
// </license>
#endregion

using System.Data;
using System.Data.Common;
using System.Data.Objects;

namespace SQLServer.Repository.DAL.RepositoryDao.Extensions
{
    public static class ObjectContextExtensions
    {
        /// <summary>
        /// Execute a store procedure without results returns
        /// </summary>
        /// <param name="objectContext">ObjectContext</param>
        /// <param name="storeProcedureName">Name of store procedure</param>
        public static void ExecuteStoreProcedure(this ObjectContext objectContext, string storeProcedureName)
        {
            objectContext.Connection.Open();
            DbCommand command = objectContext.Connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = objectContext.DefaultContainerName + "." + storeProcedureName;
            command.ExecuteNonQuery();
        }

        ///<summary>
        /// Execute store procedure not mapping on edmx model
        ///</summary>
        ///<param name="objectContext">ObjectContext</param>
        ///<param name="storeProcedureName">Name of store procedure</param>
        ///<param name="parameters">Parameters of strore procedure</param>
        ///<param name="useOracleSyntax">if is an Oracle's stored procedure</param>
        public static void ExecuteStoreProcedureNotMapping(this ObjectContext objectContext, string storeProcedureName, object[] parameters, bool useOracleSyntax = false)
        {
            string commandToExecute = string.Empty;

            if (useOracleSyntax)
                commandToExecute = "begin ";

            commandToExecute += storeProcedureName + "(";
            foreach (var parameter in parameters)
            {
                commandToExecute += parameter.GetType().IsValueType ? parameter + "," : "'" + parameter.ToString().Replace("'", "''") + "',";
            }
            commandToExecute = commandToExecute.Substring(0, commandToExecute.Length - 1) + ")";

            if (useOracleSyntax)
                commandToExecute += "; end;";

            objectContext.ExecuteStoreCommand(commandToExecute);
        }
    }
}
